package com.logistics.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.logistics.compont.ResponseApi;
import com.logistics.entity.LoginUser;
import com.logistics.pojo.Employee;
import com.logistics.service.LoginService;
import com.logistics.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 认证管理器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public ResponseApi<Employee> login(Employee employee) {

        //通过UsernamePasswordAuthenticationToken获取用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(employee.getUsername(),employee.getPassword());

        //AuthenticationManager委托机制对authenticationToken 进行用户认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没有通过，给出对应的提示
        if (ObjectUtils.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        //如果认证通过，使用user生成jwt  jwt存入ResponseResult 返回
        //如果认证通过，拿到这个当前登录用户信息
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();

        //脱敏
        loginUser.setPassword(null);

        //获取当前用户的userid
        Employee emp = loginUser.getEmployee();

        //存入token信息 可以是emp对象；也可以封装到map数据结构中 为了 延展
//        Map<String,Object> jwtMap = new HashMap<String,Object>();
//        jwtMap.put("emp",emp);

        String token = JwtUtil.createJWT(JSON.toJSONString(emp));

        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);

        //把完整的用户信息存入redis  userid为key   用户信息为value
        stringRedisTemplate.boundHashOps("com.logistics:loginUser").put("login:"+emp.getEid(), JSON.toJSONString(loginUser));

        //失效策略
        stringRedisTemplate.expire("loginUser",2, TimeUnit.HOURS);

        return ResponseApi.SUCCESS(tokenMap);
    }

    @Override
    public ResponseApi<Employee> loginOut() {

        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        //获取当前登录用户
        LoginUser loginUser = (LoginUser) authenticationToken.getPrincipal();
        Integer eid = loginUser.getEmployee().getEid();

        stringRedisTemplate.boundHashOps("com.logistics:loginUser").delete("login:"+eid);

        return ResponseApi.SUCCESS("退出成功。");
    }


}
